<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="main.css">
    <title>博客详情</title>
</head>

<body>
<h1 id="title" class="title"></h1>
<div id="info-container" class="info-container"></div>
<div class="content-wrapper">
    <p id="content"></p>
</div>

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdn.bootcss.com/moment.js/2.24.0/locale/zh-cn.js"></script>
<script type="text/javascript">
    /*发送get请求*/
    function get(url) {
        return $.get(url);
    }

    /*显示格式化时间*/
    function getFormatDate(dt) {
        return moment(dt).format('LL');
    }

    /*抽离成可配置的匹配列表*/
    const matchList = {
        '&lt;': '<',
        '&gt;': '>',
        '&amp;': '&',
        '&#34;': '"',
        '&quot;': '"',
        '&#39;': "'",
    };

    /*字符过滤器*/
    const htmlDecode = (text) => {
        let regStr = '(' + Object.keys(matchList).toString() + ')';
        // 通过匹配将其更新为正则的字符串类型
        regStr = regStr.replace(/,/g, ')|(');
        // 字符串 转 正则 方法
        const regExp = new RegExp(regStr, 'g');
        // 替换方法 (正则, 当前key => 返回当前被匹配的key值)
        return text.replace(regExp, match => matchList[match]);
    };

    /*获取 url 参数*/
    function getUrlParams() {
        let paramStr = location.href.split('?')[1] || '';
        paramStr = paramStr.split('#')[0];
        const result = {};
        paramStr.split('&').forEach(itemStr => {
            const arr = itemStr.split('=');
            const key = arr[0];
            result[key] = arr[1];
        });
        return result;
    }

    /*获取 dom 元素*/
    const $title = $('#title');
    const $infoContainer = $('#info-container');
    const $content = $('#content');

    const urlParams = getUrlParams();
    const url = '/api/blog/detail?id=' + urlParams.id;
    get(url).then(res => {
        if (res.errno !== 0) {
            alert('操作错误');
            return;
        }
        /*显示数据*/
        const data = res.data || {};
        $title.text(htmlDecode(data.title));
        $content.text(htmlDecode(data.content));
        $infoContainer.append($(`
            <span>
                <a href="/index.html?author=${data.author}">${data.author}</a>
            </span>
            <span>${getFormatDate(data.createtime)}</span>
        `));
    });
</script>
</body>

</html>